package com.zyx.springmvcmsb.response.controller;

import com.zyx.springmvcmsb.response.bean.Person;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zyx
 * @since 2021/10/5 08:33
 */
@Controller
public class ValidationController {

    @RequestMapping("/validation")
    public String validate(@Valid Person person, BindingResult bindingResult, Model model) {
        System.out.println(person);
        Map<String, Object> map = new HashMap<>(1 << 4);
        if (bindingResult.hasErrors()) {
            System.out.println("登录失败");
            // 获取当前所有的错误
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String msg = fieldError.getDefaultMessage();
                System.out.println("field =====>>>>> " + field);
                System.out.println("message =====>>>>> " + msg);
                map.put(field, msg);
            }
            model.addAttribute("errors", map);
            return "forward:/login.jsp";
        } else {
            System.out.println("登录成功");
            return "success";
        }
    }
}
